<template>
  <Container>
    <!-- 标题内容 -->
    <main
      class="content"
      @scroll="handleScroll"
    >
      <div class="header">
        <div class="header-left">
          <h2>我的提问箱</h2>

          <!-- 关注提问箱按钮 -->
          <el-button
            :class="isFollowed ? 'followed-btn' : 'follow-btn'"
            @click="toggleFollow"
          >
            {{ isFollowed ? '取消关注' : '关注提问箱' }}
          </el-button>
        </div>

        <!-- 使用搜索框组件 -->
        <SearchBox @update:search="handleSearch" />

        <el-button
          :class="'follow-btn'"
          @click="openDialog()"
        >
          发起提问
        </el-button>
      </div>
      <!-- 内容卡片 -->
      <questioncard
        v-for="item in allItems"
        :key="item.id"
        :item="item"
      ></questioncard>
      <!-- 提问弹窗 -->
      <el-dialog
        title="发起提问"
        v-model="dialogVisible"
        width="50%"
        :style="{ height: '500px' }"
      >
        <el-form
          :model="formData"
          label-width="80px"
        >
          <el-form-item label="标题">
            <el-input v-model="formData.title" />
          </el-form-item>
          <el-form-item label="内容">
            <el-input
              v-model="formData.content"
              type="textarea"
              rows="10"
            />
          </el-form-item>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="closeDialog">取消</el-button>
          <el-button
            type="primary"
            @click="saveQuestion"
          >保存</el-button>
        </div>
      </el-dialog>
    </main>
  </Container>
</template>
  
<script setup>
import Container from '../components/main/container.vue';
import questioncard from '../components/main/questioncard.vue';
import { ref, computed, onMounted } from 'vue';
import { get, post } from "@/net";
import { ElMessage } from 'element-plus';
import { useAccountStore } from "@/store";
import SearchBox from '../components/main/searchbox.vue';

const props = defineProps({
  id: {
    type: Number,
    required: true
  }
})
const query = ref("")//搜索栏语句
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(50)
const aid = ref(1)
const allItems = ref([])
const isFollowed = ref(false)
const dialogVisible = ref(false); // 控制弹窗显示
const formData = ref({
  title: '',
  content: ''
}); // 存储提问数据
// 打开弹窗
const openDialog = () => {
  dialogVisible.value = true;
  formData.value = {
    title: '',
    content: ''
  };
};

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};
const store = useAccountStore();
// 保存提问
const saveQuestion = async () => {
  if (!formData.value.title || !formData.value.content) {
    ElMessage.error('请填写完整的提问信息');
    return;
  }

  // 将数据发送到后端
  post(
    "/question_info/create_question",
    {
      bid: props.id,
      title: formData.value.title,
      content: formData.value.content,
      questioner_id: store.account.id
    }, // 提交标题和内容
    (message) => {
      ElMessage.success('提问成功');
      closeDialog(); // 关闭弹窗
      // 清空现有数据并重新加载
      allItems.value = []; // 清空已有提问
      currentPage.value = 1; // 重置页码
      fetchData(); // 重新请求数据
    },
    () => {
      ElMessage.error('提问失败，请稍后重试');
    }
  );
  post(
    "/message_info/add_message",
    {
      receiver_id: props.id,
      sender_id: store.account.id,
      tex: "收到一个新提问",
      message_type: 3
    }, // 提交标题和内容
    (message) => {
    }
  );
};
const fetchData = async () => {
  if (query.value == "") {
    get(
      "/question_info/get_questions_from_box", { bid: props.id, pageNum: currentPage.value, pageSize: pageSize.value, aid: store.account.id },
      (message) => {
        console.log(message.data);
        allItems.value.push(...message.data.questions); // 累加提问
        // totalItems.value = message.data.total;
      },
      () => {
        store.clearAccount();
      }
    );
  }
  else {
    //console.log("搜索");
    get(
      "/question_info/search_question",
      {
        bid: props.id,
        keyword: query.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      },
      (message) => {
        allItems.value.push(...message.data.questions);
      },
      () => {
        store.clearAccount();
      }
    );
  }
};

const is_join = async () => {
  get(
    "/question_box/is_join", { aid: store.account.id, bid: props.id },
    (message) => {
      console.log(message.msg);
      isFollowed.value = true;
    },
    (message) => {
      console.log(message.msg);
      isFollowed.value = false;
    }
  );
}

onMounted(() => {
  fetchData(); // 组件加载时请求数据
  is_join();
});

// 监听滚动事件，判断是否滚动到底部
let timeout;
const handleScroll = (event) => {
  console.log("scrollHeight:", event.target.scrollHeight);
  console.log("scrollTop:", event.target.scrollTop);
  console.log("clientHeight:", event.target.clientHeight);
  clearTimeout(timeout);
  timeout = setTimeout(() => {
    const bottom = (Math.abs(event.target.scrollHeight - (event.target.scrollTop + event.target.clientHeight)) < 1);
    if (bottom && allItems.value.length < totalItems.value) {
      currentPage.value += 1;
      fetchData();
    }
  }, 100); // 延迟 150ms 触发滚动逻辑
};

// 关注提问箱
const toggleFollow = () => {
  isFollowed.value = !isFollowed.value;
  // 调用后端接口，关注或取消关注提问箱
  if (isFollowed.value) {
    post('/message_info/add_message', { receiver_id: props.id, sender_id: store.account.id, tex: "加入了提问箱", message_type: 6 }, (message) => {
      console.log(message.msg);
    });
  };
  post(
    "/question_box/join",
    {
      aid: store.account.id,
      bid: props.id,
    },
    (message) => {
      console.log(message.msg);
    }
  );
};
const handleSearch = async (keyword) => {
  query.value = keyword;
  allItems.value = [];
  currentPage.value = 1;
  fetchData();
};
</script>

<style scoped>
.content {
  height: 100%;
  padding: 20px;
  gap: 20px;
  background-color: #f5f5f5;
  overflow-y: auto; /* 允许垂直滚动 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px; /* 设置标题和按钮之间的间距 */
}

.follow-btn {
  background-color: orange; /* 橙色背景 */
  border-color: orange;
  color: white;
}

.follow-btn:hover {
  background-color: darkorange; /* 橙色按钮的悬停效果 */
}

.followed-btn {
  background-color: rgb(173, 149, 54); /* 灰色背景，禁用样式 */
  border-color: rgb(173, 149, 54);
  color: white;
}
</style>
